package com.ibeeking.found.common.utils;


import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {
    private static HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

    static {
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    public static String getCharacterPinYin(char c) {
        try {
            String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
            if (null == pinyin || pinyin.length < 1)
                return null;
            return pinyin[0];
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            return null;
        }
    }

    public static String getPinYin(String str) {
        if (null == str || "".equals(str.trim()))
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            String pinyin = getCharacterPinYin(str.charAt(i));
            if (null != pinyin && 0 == i)
                sb.append("~");
            sb.append((null == pinyin) ? Character.valueOf(str.charAt(i)) : pinyin);
        }
        return sb.toString();
    }

    public static String getSortPinYin(String str) {
        if (null == str || "".equals(str.trim()))
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            String pinyin = getCharacterPinYin(str.charAt(i));
            if (null != pinyin && 0 == i)
                sb.append("~");
            sb.append((null == pinyin) ? Character.valueOf(str.charAt(i)) : pinyin);
        }
        return sb.toString().toLowerCase();
    }
}
